/*
 *  Copyright 2005 Blandware (http://www.blandware.com)
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.blandware.atleap.webapp.action.forum.forum;

import com.blandware.atleap.common.TestimonialModuleConstants;
import com.blandware.atleap.common.ForumModuleConstants;
import com.blandware.atleap.common.util.QueryInfo;
import com.blandware.atleap.model.testimonials.Testimonial;
import com.blandware.atleap.model.forum.Forum;
import com.blandware.atleap.service.testimonials.TestimonialManager;
import com.blandware.atleap.service.forum.ForumManager;
import com.blandware.atleap.webapp.action.core.grid.BaseGridAction;
import com.blandware.atleap.webapp.taglib.core.grid.util.Grid;
import com.blandware.atleap.webapp.taglib.core.grid.util.SortField;
import com.blandware.atleap.webapp.util.core.WebappConstants;
import com.blandware.atleap.webapp.util.core.WebappUtil;
import com.blandware.atleap.webapp.util.forum.ForumModuleWebConstants;
import com.blandware.atleap.webapp.util.forum.ForumModuleWebUtil;
import com.blandware.atleap.webapp.util.testimonials.TestimonialModuleWebConstants;
import org.apache.struts.Globals;
import org.apache.struts.action.*;
import org.apache.commons.validator.GenericValidator;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.*;

/**
 * <p>Shows list of forums for administration.</p>
 * <p><a href="ListForumsAction.java.html"><i>View source</i></a></p>
 *
 * @author Roman Puchkovskiy <a href="mailto:roman.puchkovskiy@blandware.com">
 *         &lt;roman.puchkovskiy@blandware.com&gt;</a>
 * @version $Revision: 1.3 $ $Date: 2006/10/31 11:55:54 $
 * @struts.action path="/forum/forum/list"
 * name="forumForm"
 * validate="false"
 * roles="forum-forum-list"
 * @struts.action-forward name="listForums"
 * path=".forum.forum.list"
 */
public final class ListForumsAction extends BaseGridAction {
	/**
	 * @param mapping  The ActionMapping used to select this instance
	 * @param form     The optional ActionForm bean for this request (if any)
	 * @param request  The HTTP request we are proceeding
	 * @param response The HTTP response we are creating
	 * @return an ActionForward instance describing where and how
	 *         control should be forwarded, or null if response
	 *         has already been completed
	 */
	public ActionForward execute(ActionMapping mapping, ActionForm form,
	                             HttpServletRequest request,
                                 HttpServletResponse response) throws Exception {

        HttpSession session = request.getSession();

        boolean showRoot = "true".equalsIgnoreCase((String) request.getParameter("showRoot"));

        Long parentId = null;
        if (!showRoot) {
            if (!GenericValidator.isBlankOrNull((String) request.getParameter("parentId"))) {
                try {
                    parentId = Long.valueOf((String) request.getParameter("parentId"));
                } catch (NumberFormatException e) {
                    parentId = null;
                }
            } else if (session.getAttribute(ForumModuleWebConstants.FORUM_PARENT_ID_KEY) != null) {
                parentId = (Long) session.getAttribute(ForumModuleWebConstants.FORUM_PARENT_ID_KEY);
            }
        }

        Forum parent = null;
        List parentsList = new ArrayList();

        if (parentId != null) {
            // check whether parent exists
            ForumManager forumManager = (ForumManager) getBean(ForumModuleConstants.FORUM_MANAGER_BEAN);
            parent = forumManager.retrieveForum(parentId);
            if (parent == null) {
                // parent not found - it might has been deleted
                ActionMessages errors = new ActionMessages();
                errors.add("parentNotFound", new ActionMessage("forum.forum.errors.parentNotFound"));
                saveErrors(request, errors);
                session.removeAttribute(ForumModuleWebConstants.FORUM_PARENT_ID_KEY);
                return mapping.findForward("listForums");
            }

            parentsList = ForumModuleWebUtil.getForumParentsList(parent, forumManager);
        }

        Long grandParentId = null;
        if (parent != null && parent.getParent() != null) {
            grandParentId = parent.getParent().getId();
        }

        ForumManager forumManager = (ForumManager) getBean(ForumModuleConstants.FORUM_MANAGER_BEAN);
        Integer[] positions = forumManager.getFirstLastForumOccupiedPositions(parentId);
        Integer minPosition = positions[0];
        Integer maxPosition = positions[1];

        session.setAttribute(ForumModuleWebConstants.FORUM_PARENT_ID_KEY, parentId);
        session.setAttribute(ForumModuleWebConstants.FORUM_GRAND_PARENT_ID_KEY, grandParentId);
        request.setAttribute(ForumModuleWebConstants.FORUM_PARENTS_LIST_KEY, parentsList);
        request.setAttribute(ForumModuleWebConstants.FORUM_MIN_POSITION_KEY, minPosition);
        request.setAttribute(ForumModuleWebConstants.FORUM_MAX_POSITION_KEY, maxPosition);

		// save transaction token in request
		saveToken(request);
		return mapping.findForward("listForums");
	}
}
